import axios from 'axios';
import store from 'src/vuex/store';
import { messages } from 'src/locales';
import API_LIST from 'src/API_LIST';
import responseInterceptor from './response-interceptor';
import { showLottieLoading, hideLottieLoading } from './global-loading'

const lang_type = store.state.lang.current_lang;

/**
 * 请求发出前处理
 * @param {Object} config
 * @return {*}
 */
function axiosRequestResolve(config) {
	if (!config.hideLoading) {
    showLottieLoading();
  }

	// // // @see {@link https://github.com/mzabriskie/axios/issues/209}
	// if(openid) config.headers.Authorization =  `Bearer ${openid}`;

	return config;
}
/**
 * 对请求错误处理后件
 */
function axiosRequestReject(error) {
	return Promise.reject(error);
}

/**
 * 对响成功处理
 * @param response
 * @return {*}
 */
function axiosResponseResolve(response) {
  hideLottieLoading();

	if (API_LIST.APP_DEBUG) {
		return responseInterceptor(response);
	}
	return response;
}

/**
 * 响应错误处理
 * @param error
 * @return {Promise.<*>}
 */
function axiosResponseReject(error) {
	hideLottieLoading();

	if (!error.response) return Promise.reject(error);

	switch (error.response.status) {
	case 404:

		return Promise.reject(new Error(messages[lang_type].common.request_error));
	case 405:

		return Promise.reject(new Error(messages[lang_type].common.request_forbidden));
	case 429:

		return Promise.reject(new Error(messages[lang_type].common.request_too_much));
	case 500:

		return Promise.reject(new Error(messages[lang_type].common.network_exception));

	default:
		return Promise.reject(error);
	}
}

// 请求拦截器
axios.interceptors.request.use(axiosRequestResolve, axiosRequestReject);

// 响应拦截器
axios.interceptors.response.use(axiosResponseResolve, axiosResponseReject);

export default axios;
